
package de.uni.wuppertal.server.ftp;

import java.io.*;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * @author Martin Schröder
 * @author Patrik Nordsiek
 */
public class FTPServerDataConnection
{
	private Socket socket;
	private OutputStream out;
	private BufferedWriter writer;
	
	private static DateFormat listDateFormat;
	
	static
	{
		listDateFormat = new SimpleDateFormat("MMM dd HH:mm ", new Locale("en"));
		listDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
	}
	
	public FTPServerDataConnection(FTPServer server, Socket socket) throws Throwable
	{
		this.socket = socket;
		
		out = socket.getOutputStream();
		
		writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 4096);
	}
	
	public void close()
	{
		if(!socket.isClosed())
		{
			try
			{
				socket.close();
			}
			catch(Throwable t)
			{
			}
		}
	}
	
	public void execListCommand(File directory) throws Throwable
	{
		try
		{
			for(File entry : directory.listFiles())
			{
				StringBuffer buffer = new StringBuffer(400);
				
				if(entry.isFile())
				{
					buffer.append("-rw-r--r-- 1 owner group ");
					
					String size = String.valueOf(entry.length());
					
					for(int i = size.length() - 1; i < 13; i++)
					{
						buffer.append(' ');
					}
					
					buffer.append(size);
					buffer.append(' ');
				}
				else if(entry.isDirectory())
				{
					buffer.append("drwxr-xr-x 1 owner group            0 ");
				}
				else
				{
					continue;
				}
				
				Date lastModified = new Date(entry.lastModified());
				buffer.append(listDateFormat.format(lastModified));
				
				buffer.append(entry.getName());
				
				writer.write(buffer.toString());
				writer.write(FTPServer.CRLF);
			}
			
			writer.flush();
		}
		finally
		{
			close();
		}
	}
	
	public void execRetrieveCommand(File file) throws Throwable
	{
		try
		{
			FileInputStream in = new FileInputStream(file);
			
			byte[] buffer = new byte[4096];
			int len = 0;
			
			while((len = in.read(buffer)) != -1)
			{
				out.write(buffer, 0, len);
			}
			
			out.flush();
			in.close();
		}
		finally
		{
			close();
		}
	}
}
